<template>
	<view>
		<up-navbar title="添加项目经历" @leftClick="leftClick" safeAreaInsetTop placeholder>
		</up-navbar>
		<up-form  labelWidth="80" labelPosition="left" :model="model1" :rules="rules"
			ref="form1">
			<up-divider></up-divider>
			<up-form-item prop="projectExperience.projectName">
				<template #label>
					<up-row>
						<up-col span="4">
							<up-text text="项目名称" align="center" size="20px"
								@blur="validateField('projectExperience.projectName')"></up-text>
						</up-col>
						<up-col offset="1" span="7">
							<up-input placeholder="请输入" font-size="20px" v-model="model1.projectExperience.projectName"
								border="none"></up-input>
							<up-text v-if="errors.projectName" color="red" :bold="true" text="请输入学校名称"></up-text>
						</up-col>
					</up-row>
				</template>
			</up-form-item>
			<up-divider></up-divider>
			<up-form-item prop="projectExperience.role">
				<template #label>
					<up-row>
						<up-col span="4">
							<up-text text="担任角色" align="center" size="20px"
								@blur="validateField('projectExperience.role')"></up-text>
						</up-col>
						<up-col offset="1" span="7">
							<up-input placeholder="请输入" font-size="20px" v-model="model1.projectExperience.role"
								border="none"></up-input>
							<up-text v-if="errors.role" color="red" :bold="true" text="请输入学校名称"></up-text>
						</up-col>
					</up-row>
				</template>
			</up-form-item>
			<up-divider></up-divider>
			<up-row>
				<up-col span="3">
					<up-text text="项目时间" align="center" size="20px"></up-text>
				</up-col>
				<up-col span="3" offset="1">
					<up-form-item prop="projectExperience.startTime" borderBottom ref="item1">
						<up-text :text="model1.projectExperience.startTime" size="20px" :color="startColor"
							@click="startShow=true"></up-text>
					</up-form-item>
					<up-text v-if="errors.startTime" color="red" :bold="true" text="请选择时间"></up-text>
				</up-col>
				<up-col span="1">
					——
				</up-col>
				<up-col span="3" offset="0.5">
					<up-form-item prop="projectExperience.endTime" borderBottom ref="item1">
						<up-text :text="model1.projectExperience.endTime" size="20px" :color="endColor"
							@click="endShow=true"></up-text>
					</up-form-item>
					<up-text v-if="errors.endTime" color="red" :bold="true" text="请选择时间"></up-text>
				</up-col>
			</up-row>
			<up-form-item prop="projectExperience.projectDescription" borderBottom ref="item1">
				<up-cell-group>
					<up-cell :border="false">
						<template #title>
							<up-text text="项目描述" size="20px" style="margin-left: -5px;"></up-text>
						</template>
					</up-cell>
					<up-cell @click="editProDes" :border="false">
						<template #title>
							<up-text :text="model1.projectExperience.projectDescription" lines="2" size="20px"
								:color="proDesColor"></up-text>
							<up-text v-if="errors.projectDescription" color="red" :bold="true" text="请输入项目描述"></up-text>
						</template>
						<template #right-icon>
							<up-icon name="arrow-right" style="margin-right: 20px;"></up-icon>
						</template>
					</up-cell>
				</up-cell-group>
			</up-form-item>
		</up-form>
		<up-datetime-picker :show="startShow" v-model="startValue" mode="year-month" @confirm="startTimeConfirm"
			@cancel="startShow=false" @close="startShow=false" :closeOnClickOverlay="true"></up-datetime-picker>
		<up-datetime-picker :show="endShow" v-model="endValue" mode="year-month" @confirm="endTimeConfirm"
			@cancel="endShow=false" @close="endShow=false" :closeOnClickOverlay="true"></up-datetime-picker>
		<view class="save">
			<up-button type="error" v-if="model1.projectExperience.resumeId != ''"
				style="margin-right: 10px;width: 200px;" size="large" text="删除" @click="delShow = true"></up-button>
			<up-button type="primary" size="large" text="保存" @click="submitForm()"></up-button>
		</view>
		<up-modal :content="content" :show="show" showCancelButton closeOnClickOverlay @confirm="submitForm()"
			@cancel="cancel" @close="show = false" contentTextAlign="center"></up-modal>
		<up-modal :content="delContent" :show="delShow" showCancelButton closeOnClickOverlay @confirm="delForm()"
			@cancel="delCancel" @close="delShow = false" contentTextAlign="center"></up-modal>
	</view>
</template>

<script>
	export default {
		onShow() {
			//获取项目内容传回的对象
			uni.getStorage({
				key: 'proMessage',
				success: (res) => {
					console.log('获取的数据：', res.data);
					this.proMessage = res.data;
				},
				fail: (err) => {
					// console.error('获取数据失败：', err);
					this.proMessage = err.data;
				},
			});
			// const jobContent = uni.getStorage('jobContent');
			console.log('proMessage:', this.proMessage); // 输出实际内容   
			if (this.proMessage !== null && this.proMessage !== undefined) {
				if (uni.getStorageSync('proMessage') !== '') {
					const data = uni.getStorageSync('proMessage');
					if (data !== 'cancel') {
						this.model1.projectExperience.projectDescription = data;
						this.proDesColor = 'black';
						uni.removeStorageSync('proMessage');
					} else {
						uni.removeStorageSync('proMessage');
					}
				} else {
					this.model1.projectExperience.projectDescription = '请输入';
					this.proDesColor = '#c4c9cf'
				}
			}
		},
		onLoad(options) {
			//获取上一个页面传回的对象
			if (options.value != null) {
				console.log(JSON.parse(options.value))
				// console.log(options.value)
				this.model1.projectExperience = JSON.parse(options.value);
				this.submitStartTime = this.convertToTimestamp(this.model1.projectExperience.startTime);
				this.submitEndTime = this.convertToTimestamp(this.model1.projectExperience.endTime);
				this.startColor = 'black';
				this.endColor = 'black';
				this.proDesColor = 'black';
			}
		},
		data() {
			return {
				model1: {
					projectExperience: {
						experienceId: '',
						resumeId: 1,
						projectName: '',
						role: '',
						startTime: '开始时间',
						endTime: '结束时间',
						projectDescription: '请输入',
					},
				},
				errors: {
					projectName: '',
					role: '',
					startTime: '',
					endTime: '',
					projectDescription: '',
				},
				//开始时间
				startShow: false,
				startColor: '#c4c9cf',
				startValue: Number(new Date()),
				//开始时间提交
				submitStartTime: '',
				//结束时间
				endShow: false,
				endColor: '#c4c9cf',
				endValue: Number(new Date()),
				//结束时间提交
				submitEndTime: '',
				//项目描述
				proDesColor: '#c4c9cf',
				proMessage: '',
				//左上角返回
				content: '是否要保存再返回',
				show: false,
				//删除
				delContent: '确定要删除该经历？',
				delShow: false,
			}
		},
		methods: {
			//判断是否为空
			validateField(field) {
				switch (field) {
					case 'projectName':
						this.errors.projectName = this.model1.projectExperience.projectName ? '' : '请输入项目名称';
						break;
					case 'role':
						this.errors.role = this.model1.projectExperience.role ? '' : '请输入角色';
						break;
					case 'startTime':
						this.errors.startTime = this.model1.projectExperience.startTime === '开始时间' ? '请选择时间' : '';
						break;
					case 'endTime':
						this.errors.endTime = this.model1.projectExperience.endTime === '结束时间' ?
							'请选择时间' : '';
						break;
					case 'projectDescription':
						this.errors.projectDescription = this.model1.projectExperience.projectDescription === '请输入' ?
							'请输入项目描述' : '';
						break;
				}
			},
			leftClick() {
				this.show = true;
			},
			//开始时间确认
			startTimeConfirm(startDate) {
				const date = new Date(startDate.value);
				if (isNaN(date.getTime())) {
					console.error('Invalid date:', startDate.value);
					return; // 处理无效日期的逻辑  
				}
				this.submitStartTime = startDate.value;
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const formattedDate = `${year}.${month}`;

				this.model1.projectExperience.startTime = formattedDate;
				this.startColor = 'black';
				this.startShow = false;
			},
			//结束时间确认
			endTimeConfirm(endDate) {
				// 检查 endDate.value 是否有效
				if (!endDate.value || isNaN(endDate.value)) {
					console.error('无效的日期值:', endDate.value);
					return; // 终止执行  
				}
				this.submitEndTime = endDate.value;
				// 将时间戳转换为 Date 对象
				const date = new Date(endDate.value);
				// 获取年份和月份  
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始，所以需要加 1，并且补零  
				// 格式化为 "年 - 月" 的形式  
				const formattedDate = `${year}.${month}`;
				//存值
				this.model1.projectExperience.endTime = formattedDate;
				//调色
				this.endColor = 'black';
				//关闭选择器
				this.endShow = false;
			},
			//将年-月转换为时间戳
			convertToTimestamp(yearMonth) {
				// 将字符串转换为日期对象  
				const [year, month] = yearMonth.split('-');
				// 创建一个新的 Date 对象，设置为该月的第一天  
				const date = new Date(year, month - 1); // month - 1 因为月份是从 0 开始的  
				// 获取时间戳（以毫秒为单位）  
				return date.getTime(); // 返回时间戳  
			},
			//将时间戳转换为dateTime形式
			changeToDateTime(timestamp) {
				const date = new Date(timestamp);

				// 获取年、月、日、时、分、秒  
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以加1  
				const day = String(date.getDate()).padStart(2, '0');
				const hours = String(date.getHours()).padStart(2, '0');
				const minutes = String(date.getMinutes()).padStart(2, '0');
				const seconds = String(date.getSeconds()).padStart(2, '0');

				// 格式化为 ISO 8601 格式  
				const dateTimeString = `${year}-${month}-${day}T${hours}:${minutes}:${seconds}.000Z`;
				return dateTimeString;
			},
			//编辑项目描述
			editProDes() {
				let str = encodeURIComponent(JSON.stringify(this.model1.projectExperience))
				uni.navigateTo({
					url: "/pages/personal/proContentView?proDescription=" + str
				})
			},
			//删除取消
			delCancel() {
				uni.navigateTo({
					url: "/pages/personal/onlineResumeView"
				})
			},
			//删除该经历
			delForm() {
				//调用数据库删除
				this.$api.delUserExp({
					id: this.model1.projectExperience.experienceId
				}).then((res) => {
					if (res.data === 'ok') {
						uni.showToast({
							title: '删除成功',
							icon: 'success',
							complete() {
								uni.navigateTo({
									url: "/pages/personal/onlineResumeView"
								})
							}
						})
					} else {
						uni.showToast({
							title: '删除失败',
							icon: 'fail',
						})
					}
				})
			},
			//返回取消
			cancel() {
				uni.navigateTo({
					url: "/pages/personal/onlineResumeView"
				})
			},
			//提交表单
			submitForm() {
				this.validateField('projectName');
				this.validateField('role');
				this.validateField('startTime');
				this.validateField('endTime');
				this.validateField('projectDescription');
				// 检查是否有错误
				let hasError = false;
				for (let key in this.errors) {
					if (this.errors[key]) {
						hasError = true;
						break;
					}
				}
				// 检查时间是否正确
				if (this.model1.projectExperience.startTime > this.model1.projectExperience.endTime) {
					uni.showToast({
						title: '开始时间必须小于结束时间',
						icon: 'none'
					});
					return;
				}
				// 检查入职时间是否大于当前时间
				if (new Date(this.model1.projectExperience.startTime) > new Date()) {
					uni.showToast({
						title: '开始时间不能大于当前时间',
						icon: 'none'
					});
					return;
				}
				if (hasError) {
					this.show = false;
					return;
				}
				if (this.model1.projectExperience.experienceId !== '') {
					//修改数据
					this.$api.updateUserProExp({
						experienceId: this.model1.projectExperience.experienceId,
						resumeId: this.model1.projectExperience.resumeId,
						projectName: this.model1.projectExperience.projectName,
						role: this.model1.projectExperience.role,
						startTime: this.changeToDateTime(this.submitStartTime),
						endTime: this.changeToDateTime(this.submitEndTime),
						projectDescription: this.model1.projectExperience.projectDescription
					}).then((res) => {
						uni.showToast({
							title: `${res.code === 200 ? '修改成功' : '修改失败'}`,
							icon: 'none'
						});
						uni.navigateTo({
							url: "/pages/personal/onlineResumeView"
						});
					})
				} else {
					this.$api.addUserProExp({
						resumeId: this.model1.projectExperience.resumeId,
						projectName: this.model1.projectExperience.projectName,
						role: this.model1.projectExperience.role,
						startTime: this.changeToDateTime(this.submitStartTime),
						endTime: this.changeToDateTime(this.submitEndTime),
						projectDescription: this.model1.projectExperience.projectDescription
					}).then((res) => {
						uni.showToast({
							title: `${res.code === 200 ? '保存成功' : '保存失败'}`,
							icon: 'none'
						});
						uni.navigateTo({
							url: "/pages/personal/onlineResumeView"
						});
					})
				}
			},
		}
	}
</script>

<style>
	.save {
		position: fixed;
		bottom: 0;
		width: 95%;
		background-color: #fff;
		padding: 10px;
		box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.1);
		display: flex;
	}

	.custom-error {
		color: blue;
		/* 修改错误提示颜色 */
		font-weight: bold;
		/* 加粗 */
		margin-top: 5px;
		/* 提示和输入框之间的间距 */
	}
</style>